package com.regulareport.web.controller.report;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.regulareport.common.annotation.Log;
import com.regulareport.common.config.RuoYiConfig;
import com.regulareport.common.core.controller.BaseController;
import com.regulareport.common.core.domain.AjaxResult;
import com.regulareport.common.core.domain.entity.ReportFormsEdit;
import com.regulareport.common.core.page.TableDataInfo;
import com.regulareport.common.enums.BusinessType;
import com.regulareport.common.utils.StringUtils;
import com.regulareport.common.utils.file.FileUtils;
import com.regulareport.common.utils.poi.ExcelUtil;
import com.regulareport.form.domain.ReportFormsEditVO;
import com.regulareport.form.service.IReportFormsEditService;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 报版本管理Controller
 * 
 * @author ruoyi
 * @date 2025-09-03
 */
@RestController
@RequestMapping("/reportForms")
public class ReportFormsEditController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(ReportFormsEditController.class);
    @Autowired
    private IReportFormsEditService reportFormsEditService;

    /**
     * 查询报版本管理列表
     */
    @PreAuthorize("@ss.hasPermi('report:forms:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportFormsEdit reportFormsEdit) {
        startPage();
        List<ReportFormsEdit> list = reportFormsEditService.selectReportFormsEditList(reportFormsEdit);
        return getDataTable(list);
    }

    /**
     * 导出报版本管理列表
     */
    @PreAuthorize("@ss.hasPermi('report:forms:export')")
    @Log(title = "报版本管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportFormsEdit reportFormsEdit) {
        List<ReportFormsEdit> list = reportFormsEditService.selectReportFormsEditList(reportFormsEdit);
        ExcelUtil<ReportFormsEdit> util = new ExcelUtil<ReportFormsEdit>(ReportFormsEdit.class);
        util.exportExcel(response, list, "报版本管理数据");
    }


    /**
     * 导入银监模板
     */
    @PreAuthorize("@ss.hasPermi('report:forms:import')")
    @Log(title = "银监模板导入", businessType = BusinessType.EXPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, MultipartFile fillFile, ReportFormsEdit reportForms) throws Exception {

        log.info("银监模板上传开始，{},{}", reportForms.getPkId(), reportForms.getEdition());
        reportForms.setPkId(reportForms.getPkId());
        reportForms.setEdition(reportForms.getEdition());
        log.info("银监模板上传  版本号==============" +reportForms.getEdition());
        int resultInt = reportFormsEditService.uploadReportFormsEdit(file, fillFile, reportForms);
        log.info("银监模板上传结束.............");
        return toAjax(resultInt);
    }

    /**
     * 获取报版本管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('report:forms:look')")
    @GetMapping(value = "/{pkId}")
    public AjaxResult getInfo(@PathVariable("pkId") Long pkId) {
        try {
            return success(reportFormsEditService.selectReportFormsEditByPkId(pkId));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 新增报版本管理
     */
    @PreAuthorize("@ss.hasPermi('system:report:add')")
    @Log(title = "报版本管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportFormsEdit reportForms) {
        ReportFormsEdit queryReportForms = new ReportFormsEdit();

        queryReportForms.setReportFormNo(reportForms.getReportFormNo());
        queryReportForms.setReportFormName(reportForms.getReportFormName());
        queryReportForms.setEdition(reportForms.getEdition());
        List<ReportFormsEdit> reFromsResult = reportFormsEditService.selectReportFormsEditList(queryReportForms);
        if (reFromsResult != null && !reFromsResult.isEmpty()) {
            return error("上传银监模板" + reportForms.getReportFormName() + ", 批次：" + reportForms.getEdition() + "失败，该模板已存在，如需上传请删除原模板");
        }
        reportForms.setCreateBy(getUsername());
        AjaxResult ajax = toAjax(reportFormsEditService.insertReportFormsEdit(reportForms));
        ajax.put("pkId", reportForms.getPkId());
        return ajax;
    }

    /**
     * 修改报版本管理
     */
    @PreAuthorize("@ss.hasPermi('report:forms:edit')")
    @Log(title = "报版本管理", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult edit(@RequestBody ReportFormsEdit reportFormsEdit) {
        reportFormsEdit.setUpdateBy(getUsername());
        return toAjax(reportFormsEditService.updateReportFormsEdit(reportFormsEdit));
    }

    @PreAuthorize("@ss.hasPermi('report:forms:edit')")
    @Log(title = "报表版本状态管理", businessType = BusinessType.UPDATE)
    @PutMapping("/updateState")
    public AjaxResult updateState(@RequestBody ReportFormsEdit reportFormsEdit) {
        reportFormsEdit.setUpdateBy(getUsername());
        try {
            reportFormsEditService.updateState(reportFormsEdit);
            return AjaxResult.success();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 删除报版本管理
     */
    @PreAuthorize("@ss.hasPermi('report:forms:delete')")
    @Log(title = "报版本管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{pkId}")
    public AjaxResult remove(@PathVariable Long pkId) {
        return toAjax(reportFormsEditService.deleteReportFormsEditByPkId(pkId));
    }

    /**
     * 删除报版本管理
     */
    @PreAuthorize("@ss.hasPermi('system:report:remove')")
    @Log(title = "报版本管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{pkIds}")
    public AjaxResult remove(@PathVariable Long[] pkIds) {
        return toAjax(reportFormsEditService.deleteReportFormsEditByPkIds(pkIds));
    }

    /**
     * 银监模板下载
     */
    @PreAuthorize("@ss.hasPermi('system:report:look')")
    @GetMapping("/exportExcel")
    public void exportExcel(String pkId, HttpServletResponse response, HttpServletRequest request)  {
        ReportFormsEditVO reportFormsEditVO = null;
        try {
            reportFormsEditVO = reportFormsEditService.selectReportFormsEditByPkId(Long.valueOf(pkId));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        try {
            if (ObjectUtils.isEmpty(reportFormsEditVO) || (ObjectUtils.isNotEmpty(reportFormsEditVO) && StringUtils.isEmpty(reportFormsEditVO.getFilePath()))) {
                throw new Exception("文件未找到，不能下载。 ");
            }
            String realFileName = reportFormsEditVO.getFilePath().substring(reportFormsEditVO.getFilePath().lastIndexOf(File.separator) + 1);
            // 构建完整文件路径
            Path filePath = Paths.get(RuoYiConfig.getProfile() + realFileName);
            File file = filePath.toFile();

            // 验证文件存在性
            if (!file.exists()) {
                throw new RuntimeException("文件不存在: " + realFileName);
            }

            String filePathStr = RuoYiConfig.getProfile() + reportFormsEditVO.getFilePath();

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePathStr, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }

//        ResponseEntity<FileSystemResource>
//        HttpHeaders headers = new HttpHeaders();
//        headers.add(HttpHeaders.CONTENT_DISPOSITION,
//                "attachment; filename=" + fileName);
//        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
//        headers.add("Pragma", "no-cache");
//        headers.add("Expires", "0");
//
//        return ResponseEntity.ok()
//                .headers(headers)
//                .contentLength(file.length())
//                .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
//                .body(new FileSystemResource(file));

    }


}